package com.share.wechat.core.service.impl;

import com.share.common.httpclient.util.HttpClientUtil;
import com.share.common.tools.json.JsonUtil;
import com.share.wechat.core.config.constant.URLConfig;
import com.share.wechat.core.config.entity.LoginSuccess;
import com.share.wechat.core.entity.UserDetail;
import com.share.wechat.core.repository.inter.UserDetailRepository;
import com.share.wechat.core.service.ConfigSystemService;
import com.share.wechat.core.service.UserDetailService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserDetailServiceImpl implements UserDetailService {
    private Logger logger = Logger.getLogger(this.getClass());
    @Resource
    private UserDetailRepository userDetailRepository;
    @Resource
    private ConfigSystemService configSystemService;

    @Override
    public UserDetail findByCode(String code) {
        //UserDetail userDetail = userDetailRepository.findByCode(code);
        //logger.info("查询到的用户信息为"+userDetail);
        //return userDetail;
        return null;
    }

    @Transactional
    @Override
    public void addOne(UserDetail userDetail) {
        userDetailRepository.save(userDetail);
    }

    @Override
    public UserDetail getUserInfo(String code) {
        String appId = configSystemService.getAppId();
        String appSecret = configSystemService.getAppSecret();
        String url = URLConfig.API_WEIXIN_QQ_USER_INFO;
        Map<String, String> parms = new HashMap<>();
        parms.put("appid", appId);//appId
        parms.put("secret", appSecret);//secret
        parms.put("js_code", code);//js_code
        parms.put("grant_type", "authorization_code");//grant_type
        String result = HttpClientUtil.doGet(url, parms);
        LoginSuccess loginSuccess = JsonUtil.jsonToPojo(result, LoginSuccess.class);
        logger.info("返回的数据为" + result);
        return null;
    }

    @Override
    public UserDetail getById(String id) {
        logger.info("传入id的信息为" + id);
        UserDetail detail = userDetailRepository.findOne(id);
        if (ObjectUtils.isEmpty(detail)) {
            logger.info("未查询到相关用户信息");
            return null;
        }
        logger.info("查找到的用户信息为" + detail);
        return detail;
    }
}

